package com.example.dao.implDao;

import com.example.dao.MenuDao;
import com.example.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Repository
public class MenuDaoImpl implements MenuDao {
    private final JdbcTemplate jdbcTemplate;
    @Autowired
    public MenuDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public List<Menu> menuList() {
        String sql = "SELECT * FROM t_menu";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Menu.class));
    }

    @Override
    public List<Menu> typeMenuList() {
        String sql = "SELECT * FROM t_menu WHERE type = 1";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Menu.class));
    }

    @Override
    public List<Menu> typeButtonList() {
        String sql = "SELECT * FROM t_menu ORDER BY id";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Menu.class));
    }

    @Override
    public List<Menu> queryMenuTree() {
        String sql = "SELECT * FROM t_menu ORDER BY id"; // 添加排序以确保父节点先于子节点
        List<Menu> allMenus = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Menu.class));
        return MenuDaoImpl.filterMenuList(allMenus);
    }

    public static List<Menu> filterMenuList(List<Menu> allMenus){
        // 构建树形结构
        Map<Long, Menu> menuMap = allMenus.stream().collect(Collectors.toMap(Menu::getId, Function.identity()));
        for (Menu menu : allMenus) {
            Long parentId = menu.getParentId();
            if (parentId != null && parentId > 0) { // 有父节点
                Menu parent = menuMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildMenu() == null) {
                        parent.setChildMenu(new ArrayList<>());
                    }
                    parent.getChildMenu().add(menu);
                }
            }
        }

        // 返回根节点（即父节点为null或0的菜单项）
        return allMenus.stream()
                .filter(menu -> menu.getParentId() == null || menu.getParentId() == 0)
                .collect(Collectors.toList());
    }
}
